<?php

class PaymentsController extends AppController {

    var $name = 'Payments';
    var $components = array('Session', 'Paypal', 'Email');
    var $uses = array('Product', 'Cart', 'Wishlist', 'Paymentmethod', 'Shipping', 'Order', 'User','Invoice');

    function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allowedActions = array('*');
    }

    function _get($var) {
        return isset($this->params['url'][$var]) ? $this->params['url'][$var] : null;
    }

    function expressCheckout($step=1) {
        $this->layout = "innerhome";
        //$this->Ssl->force();
        $this->set('step', $step);
        //first get a token
        $custom = $this->data['custom'];
        $cart_ids = explode("|", $custom);
        if ($step == 1) {

            //AA fee paypal
            if ($this->data['Payment']['invoice_id'] != "") {
                $this->Session->write('payToId', 1);
                $this->Session->write('AAFEE', 1);
                $invoices = $this->Invoice->find("first", array("conditions" => array("Invoice.id" => $this->data['Payment']['invoice_id'], "Invoice.invoice_status" => "Invoices Awaiting Payment")));
                
                $paymentInfo['Product'][0]['L_NAME'] = "Authentic Avenue fee";
                $paymentInfo['Product'][0]['L_DESC'] = "Authentic Avenue fee";
                $paymentInfo['Product'][0]['L_NUMBER'] = $invoices['Invoice']['id'];
                $paymentInfo['Product'][0]['L_AMT'] = $invoices['Invoice']['aa_fee'];
                $paymentInfo['Product'][0]['L_QTY'] = 1;    
                $paymentInfo['Order']['CUSTOM'] = $custom;
                $paymentInfo['Order']['SHIPPINGAMT'] = "0.00";
                $paymentInfo['Order']['ITEMAMT'] = $invoices['Invoice']['aa_fee'];
                $paymentInfo['Order']['TAXAMT'] = "0.00";                
                $paymentInfo['Order']['AMT'] = $invoices['Invoice']['aa_fee'];
                $paymentInfo['Order']['returnUrl'] = Configure::read('base_url') . "payments/expressCheckout/2/";
                $paymentInfo['Order']['cancelUrl'] = Configure::read('base_url') . "invoices";

                $paymentsGateway = $this->Paymentmethod->find("first", array("conditions" => array("Paymentmethod.user_id" => 1, "Paymentmethod.methodname" => "Paypal")));
                if ($paymentsGateway['Paymentmethod']['state'] == "live") {
                    $paymentInfo['paypalInfo']['API_ENDPOINT'] = "https://api-3t.paypal.com/nvp";
                    $paymentInfo['paypalInfo']['PAYPAL_URL'] = "https://www.paypal.com/webscr&cmd=_express-checkout&token=";
                } else {
                    $paymentInfo['paypalInfo']['API_ENDPOINT'] = "https://api-3t.sandbox.paypal.com/nvp";
                    $paymentInfo['paypalInfo']['PAYPAL_URL'] = "https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=";
                }
                $paymentInfo['paypalInfo']['API_USERNAME'] = $paymentsGateway['Paymentmethod']['apiuser'];
                $paymentInfo['paypalInfo']['API_PASSWORD'] = $paymentsGateway['Paymentmethod']['apipass'];
                $paymentInfo['paypalInfo']['API_SIGNATURE'] = $paymentsGateway['Paymentmethod']['apisigniture'];
                
            } else {
                $shipping_cost = $this->data['shipping_cost'];
                foreach ($cart_ids as $cart_id) {
                    $conditions['Cart.id'] = $cart_id;
                    $this->Cart->Behaviors->attach('Containable');
                    $this->Cart->contain('Shipping.shipping_method', 'User.id', 'User.Country.name', 'User.State.name', 'User.City.name', 'Product.products_weight', 'Product.id', 'Product.user_id', 'Product.category_id', 'Product.products_title', 'Product.products_price', 'Product.products_quantity', 'Product.use_paypal', 'Product.use_google_checkout', 'Product.tax_us', 'Product.products_commission', 'Product.products_commissionType', 'Product.ProductShipping', 'Product.ProductShipping.Shipping', 'Product.ProductInternationalShipping.Shipping', 'Product.ProductInternationalShipping', 'Product.Salestax', 'Product.User.username');
                    $carts[$cart_id] = $this->Cart->find("all", array("conditions" => $conditions));
                }

                //prepare array for NVP
                $i = 0;
                $sales_tax = 0;
                $itemamt = 0;

                foreach ($carts as $cart) {
                    $paymentInfo['Product'][$i]['L_NAME'] = $cart[0]['Product']['products_title'];
                    $paymentInfo['Product'][$i]['L_DESC'] = $cart[0]['Product']['products_title'];
                    $paymentInfo['Product'][$i]['L_NUMBER'] = $cart[0]['Cart']['product_id'];
                    $paymentInfo['Product'][$i]['L_AMT'] = $cart[0]['Cart']['product_cost'];
                    $paymentInfo['Product'][$i]['L_QTY'] = $cart[0]['Cart']['quantity'];
                    $sales_tax = $sales_tax + $cart[0]['Cart']['sales_tax'];
                    $itemamt = $itemamt + ($cart[0]['Cart']['product_cost'] * $cart[0]['Cart']['quantity']);
                    $i++;
                }
                $paymentInfo['Order']['CUSTOM'] = $custom;
                $paymentInfo['Order']['SHIPPINGAMT'] = $shipping_cost;
                $paymentInfo['Order']['ITEMAMT'] = $itemamt;
                $paymentInfo['Order']['TAXAMT'] = $sales_tax;
                $paymentInfo['Order']['AMT'] = $sales_tax + $shipping_cost + $itemamt;
                $paymentInfo['Order']['returnUrl'] = Configure::read('base_url') . "payments/expressCheckout/2/";
                $paymentInfo['Order']['cancelUrl'] = Configure::read('base_url') . "cart/view_cart";


                //Papal API credentials info
                $pay_to_id = $this->data['sellerID'];
                $this->Session->write('payToId', $pay_to_id);
                $paymentsGateway = $this->Paymentmethod->find("first", array("conditions" => array("Paymentmethod.user_id" => $pay_to_id, "Paymentmethod.methodname" => "Paypal")));

                if ($paymentsGateway['Paymentmethod']['state'] == "live") {
                    $paymentInfo['paypalInfo']['API_ENDPOINT'] = "https://api-3t.paypal.com/nvp";
                    $paymentInfo['paypalInfo']['PAYPAL_URL'] = "https://www.paypal.com/webscr&cmd=_express-checkout&token=";
                } else {
                    $paymentInfo['paypalInfo']['API_ENDPOINT'] = "https://api-3t.sandbox.paypal.com/nvp";
                    $paymentInfo['paypalInfo']['PAYPAL_URL'] = "https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=";
                }

                $paymentInfo['paypalInfo']['API_USERNAME'] = $paymentsGateway['Paymentmethod']['apiuser'];
                $paymentInfo['paypalInfo']['API_PASSWORD'] = $paymentsGateway['Paymentmethod']['apipass'];
                $paymentInfo['paypalInfo']['API_SIGNATURE'] = $paymentsGateway['Paymentmethod']['apisigniture'];
            }
            
            // call paypal
            $result = $this->Paypal->processPayment($paymentInfo, "SetExpressCheckout");
            //pr($result);
            $ack = strtoupper($result["ACK"]);
            //Detect Errors
            if ($ack != "SUCCESS") {
                $error = $result['L_LONGMESSAGE0'];
                $this->set('error', $error);
            } else {
                // send user to paypal
                $token = urldecode($result["TOKEN"]);
                $payPalURL = PAYPAL_URL . $token;
                $this->redirect($payPalURL);
            }
        }
        //next have the user confirm
        elseif ($step == 2) {
            //we now have the payer id and token, using the token we should get the shipping address
            //of the payer. Compile all the info into the session then set for the view.
            //Add the order total also
            //Papal API credentials info

            $pay_to_id = $this->Session->read('payToId');
            $paymentsGateway = $this->Paymentmethod->find("first", array("conditions" => array("Paymentmethod.user_id" => $pay_to_id, "Paymentmethod.methodname" => "Paypal")));

            if ($paymentsGateway['Paymentmethod']['state'] == "live") {
                $paymentInfo['paypalInfo']['API_ENDPOINT'] = "https://api-3t.paypal.com/nvp";
                $paymentInfo['paypalInfo']['PAYPAL_URL'] = "https://www.paypal.com/webscr&cmd=_express-checkout&token=";
            } else {
                $paymentInfo['paypalInfo']['API_ENDPOINT'] = "https://api-3t.sandbox.paypal.com/nvp";
                $paymentInfo['paypalInfo']['PAYPAL_URL'] = "https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=";
            }

            $paymentInfo['paypalInfo']['API_USERNAME'] = $paymentsGateway['Paymentmethod']['apiuser'];
            $paymentInfo['paypalInfo']['API_PASSWORD'] = $paymentsGateway['Paymentmethod']['apipass'];
            $paymentInfo['paypalInfo']['API_SIGNATURE'] = $paymentsGateway['Paymentmethod']['apisigniture'];
            $paymentInfo['TOKEN'] = $this->_get('token');

            $result = $this->Paypal->processPayment($paymentInfo, "GetExpressCheckoutDetails");
            $result['PAYERID'] = $this->_get('PayerID');
            $result['TOKEN'] = $this->_get('token');
 
            $ack = strtoupper($result["ACK"]);
            //Detect errors
            if ($ack != "SUCCESS") {
                $error = $result['L_LONGMESSAGE0'];
            } else {

                $this->create_order($result);
                $this->set('result', $result);
                $this->Session->write('result', $result);
                /*
                 * Result at this point contains the below fields. This will be the result passed 
                 * in Step 3. I used a session, but I suppose one could just use a hidden field
                 * in the view:[TOKEN] [TIMESTAMP] [CORRELATIONID] [ACK] [VERSION] [BUILD] [EMAIL] [PAYERID]
                 * [PAYERSTATUS]  [FIRSTNAME][LASTNAME] [COUNTRYCODE] [SHIPTONAME] [SHIPTOSTREET]
                 * [SHIPTOCITY] [SHIPTOSTATE] [SHIPTOZIP] [SHIPTOCOUNTRYCODE] [SHIPTOCOUNTRYNAME]
                 * [ADDRESSSTATUS] [ORDERTOTAL]
                 */
            }
        }
        //show the confirmation
        elseif ($step == 3) {
            $pay_to_id = $this->Session->read('payToId');
            $paymentsGateway = $this->Paymentmethod->find("first", array("conditions" => array("Paymentmethod.user_id" => $pay_to_id, "Paymentmethod.methodname" => "Paypal")));

            if ($paymentsGateway['Paymentmethod']['state'] == "live") {
                $paymentInfo['paypalInfo']['API_ENDPOINT'] = "https://api-3t.paypal.com/nvp";
                $paymentInfo['paypalInfo']['PAYPAL_URL'] = "https://www.paypal.com/webscr&cmd=_express-checkout&token=";
            } else {
                $paymentInfo['paypalInfo']['API_ENDPOINT'] = "https://api-3t.sandbox.paypal.com/nvp";
                $paymentInfo['paypalInfo']['PAYPAL_URL'] = "https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=";
            }

            $paymentInfo['paypalInfo']['API_USERNAME'] = $paymentsGateway['Paymentmethod']['apiuser'];
            $paymentInfo['paypalInfo']['API_PASSWORD'] = $paymentsGateway['Paymentmethod']['apipass'];
            $paymentInfo['paypalInfo']['API_SIGNATURE'] = $paymentsGateway['Paymentmethod']['apisigniture'];
            $paymentInfo['TOKEN'] = $this->Session->read('result.TOKEN');
            $paymentInfo['PAYERID'] = $this->Session->read('result.PAYERID');
            $paymentInfo['ORDERTOTAL'] = $this->Session->read('result.AMT');
            $result = $this->Paypal->processPayment($paymentInfo, "DoExpressCheckoutPayment");
            //Detect errors
            $ack = strtoupper($result["ACK"]);
            if ($ack != "SUCCESS") {
                $error = $result['L_LONGMESSAGE0'];
                $this->set('error', $error);
            } else {
                $this->update_order($result);
                $this->set('result', $result);
                $this->Session->setFlash(__('Thank you for your order from Authentic Avenue.', true));
                if($this->Session->read('AAFEE')=="1"){
                    $this->Session->write('AAFEE',"0");
                    $this->redirect(array('controller' => 'invoices', 'action' => 'index'));
                }
                else
                    $this->redirect(array('controller' => 'carts', 'action' => 'order_list'));
            }
        }
    }

    function create_order($POST) {
        $product_cost = 0;
        $cart_ids = explode("|", $POST['CUSTOM']);
        if ($cart_ids[0] == "AAFEE") {
            $datas['Invoice']['id'] = $cart_ids[1];
            $datas['Invoice']['token'] = $POST['TOKEN'];
            $this->Invoice->save($datas['Invoice']);
            //$this->emailuser($POST, '0');
        } else {
            foreach ($cart_ids as $cart_id) {
                if ($cart_id > 0) {
                    $carts = $this->Cart->find("first", array("conditions" => array("Cart.id" => $cart_id)));
                    $seller_id = $carts['Cart']['seller_id'];
                    //$product_cost = $product_cost + ($carts['Cart']['product_cost'] * $carts['Cart']['quantity']);
                }
            }
            $Order['product_cost'] = $POST['ITEMAMT'];
            $Order['shipping_cost'] = $POST['SHIPPINGAMT'];
            $Order['payment_status'] = 'Pending';
            $Order['seller_id'] = $seller_id;
            $Order['token'] = $POST['TOKEN'];
            $Order['add_date'] = date("Y-m-d H:i:s");
            $Order['order_details'] = serialize($POST);
            $this->loadModel('AddressBook');
            $this->loadModel('AddressBookField');
            $this->AddressBook->recursive = 2;
            $AddressBook=$this->AddressBook->find('first', array('conditions' => array('AddressBook.user_id' => $this->Auth->User('id'), 'use_in_cart' => "yes")));
            if($AddressBook){
            $Order['billing_first_name']=$AddressBook['AddressBookField']['first_name'];
            $Order['billing_last_name']=$AddressBook['AddressBookField']['last_name'];
            $Order['billing_address1']=$AddressBook['AddressBookField']['address_line_1'];
            $Order['billing_address2']=$AddressBook['AddressBookField']['address_line_2'];
            $Order['billing_country']=$AddressBook['AddressBookField']['Country']['name'];
            $Order['billing_city']=$AddressBook['AddressBookField']['City']['name'];
            $Order['billing_state']=$AddressBook['AddressBookField']['State']['name'];
            $Order['billing_zip']=$AddressBook['AddressBookField']['zip'];
            
            $Order['shipping_first_name']=$AddressBook['AddressBookField']['first_name'];
            $Order['shipping_last_name']=$AddressBook['AddressBookField']['last_name'];
            $Order['shipping_address1']=$AddressBook['AddressBookField']['address_line_1'];
            $Order['shipping_address2']=$AddressBook['AddressBookField']['address_line_2'];
            $Order['shipping_country']=$AddressBook['AddressBookField']['Country']['name'];
            $Order['shipping_city']=$AddressBook['AddressBookField']['City']['name'];
            $Order['shipping_state']=$AddressBook['AddressBookField']['State']['name'];
            $Order['shipping_zip']=$AddressBook['AddressBookField']['zip'];
            }
            else{
            $this->loadModel('Country');
            $this->loadModel('State');
            $this->loadModel('City');
            $country=$this->Country->country_name($this->Auth->User('country_id'));
           
            $state=$this->State->state_name($this->Auth->User('state_id'));
            $city=$this->City->city_name($this->Auth->User('city_id'));
            $Order['billing_first_name']=$this->Auth->User('first_name');
            $Order['billing_last_name']=$this->Auth->User('last_name');
            $Order['billing_address1']=$this->Auth->User('address');
            $Order['billing_address2']=$this->Auth->User('address2');
            $Order['billing_country']=$country['Country']['name'];
            $Order['billing_city']=$city['City']['name'];
            $Order['billing_state']=$state['State']['name'];
            $Order['billing_zip']=$this->Auth->User('zip');
            
            $Order['shipping_first_name']=$this->Auth->User('first_name');
            $Order['shipping_last_name']=$this->Auth->User('last_name');
            $Order['shipping_address1']=$this->Auth->User('address');
            $Order['shipping_address2']=$this->Auth->User('address2');
            $Order['shipping_country']=$country['Country']['name'];
            $Order['shipping_city']=$city['City']['name'];
            $Order['shipping_state']=$state['State']['name'];
            $Order['shipping_zip']=$this->Auth->User('zip');
            }
            $this->Order->save($Order);
            $order_id = $this->Order->getlastinsertid();
            if ($order_id > 0) {
                foreach ($cart_ids as $cart_id) {
                    if ($cart_id > 0) {
                        $Cart['id'] = $cart_id;
                        $Cart['order_id'] = $order_id;
                        $Cart['token'] = $POST['TOKEN'];
                        if ($this->Cart->save($Cart)) {
                            // $this->emailuser($POST, '0');
                        }
                    }
                }
            }
        }
    }

    function update_order($POST) {
        //$cart_ids = explode("|", $POST['CUSTOM']);
        if ($this->Session->read("AAFEE") == "1") {
            $this->Invoice->recursive=-1;
            $Invoice = $this->Invoice->find("first", array("conditions" => array("Invoice.token" => $POST['TOKEN']), "fields" => array('Invoice.id')));

            $datas['Invoice']['id'] = $Invoice['Invoice']['id'];
            $datas['Invoice']['transaction_id'] = $POST['TRANSACTIONID'];
            $datas['Invoice']['invoice_status'] = "Paid Invoices";
            $datas['Invoice']['pay_date'] = date("Y-m-d H:i:s");
            $this->Invoice->save($datas['Invoice']);
            $this->emailuser($POST, '1');
        } else {
            //update cart
            $carts = $this->Cart->find("all", array("conditions" => array("Cart.token" => $POST['TOKEN']), "fields" => array('Cart.id', 'Cart.quantity', 'Cart.product_id')));

            if ($carts) {
                foreach ($carts as $cart) {
                    $Cart['id'] = $cart['Cart']['id'];
                    $Cart['payment_status'] = 1;
                    $this->Cart->save($Cart);
                    //$carts = $this->Cart->find("first", array("conditions" => array("Cart.id" => $Cart['id'])));
                    $this->Product->query("UPDATE authentic_products SET product_totalsell=product_totalsell+" . $cart['Cart']['quantity'] . ",products_quantity=products_quantity-" . $cart['Cart']['quantity'] . " WHERE id='" . $cart['Cart']['product_id'] . "'");
                }
            }
            //update order
            $orders = $this->Order->find("first", array("conditions" => array("Order.token" => $POST['TOKEN']), "fields" => array('Order.id')));
            if ($orders['Order']['id'] > 0) {
                $Order['id'] = $orders['Order']['id'];
                $Order['payment_status'] = "Complete";
                $Order['add_date'] = date("Y-m-d H:i:s");
                $Order['transaction_id'] = $POST['TRANSACTIONID'];
                $Order['order_details'] = serialize($POST);
                if ($this->Order->save($Order)) {
                    $this->emailuser($POST, '1');
                }
            }
        }
    }

    function emailuser($options, $status=0) {
        $this->layout = null;
        $this->autoRender = false;
        if($this->Session->read('AAFEE')=="1"){
            $this->Invoice->recursive=-1;
            $invoice = $this->Invoice->find("first", array("conditions" => array("Invoice.token" => $POST['TOKEN'])));
            $this->Email->subject = 'Authentic Avenue: New Order # ' . $invoice['Invoice']['id'];
            $this->set('emailType','invoice');
            $this->set('invoice', $invoice);        
        }else{
        $carts = $this->Cart->find("all", array("conditions" => array("Cart.token" => $options['TOKEN'])));
        $orders = $this->Order->find("first", array("conditions" => array("Order.token" => $options['TOKEN'])));
        $this->set('orders', $carts);
        $this->set('orders', $orders);        
        $this->set('emailType','order');
        }
        
        $this->User->recursive = -1;
        $userinfo = $this->User->find("first", array("conditions" => array("User.id" => $this->Session->read('Auth.User.id'))));

        $this->Email->to = $userinfo['User']['username'] . ' < ' . $userinfo['User']['email'] . ' >';
        //$this->Email->to = 'Sahbaj Uddin <sahbajuddin@yahoo.com>';        
        $this->Email->from = 'authenticavenue.com < noreply@authenticavenue.com >';
        $this->Email->template = 'order_invoice';
        $this->Email->sendAs = 'html';
        $this->set('userinfo', $userinfo);
        $this->set('status', $status);
        
        //$this->set('order_date', $cart['Cart']['add_date']);
        $this->Email->send();
    }

}

?>
